package com.example.statistics.ui.bank

import android.os.Bundle
import com.example.statistics.R
import com.example.statistics.bean.IncomeExpenseBean
import com.example.statistics.common.BaseLoadingListActivity
import com.example.statistics.ex.*
import com.example.statistics.net.UrlConfig
import com.example.statistics.ui.bank.Config.toStatementActivity
import com.example.statistics.utils.Constants
import com.example.statistics.utils.DefaultConfig
import com.example.statistics.utils.activityForResult
import com.jhj.slimadapter.SlimAdapter
import com.jhj.slimadapter.holder.ViewInjector
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast


/**
 * 银行流水对账单
 */
abstract class BaseIncomeExpenseListActivity : BaseLoadingListActivity<IncomeExpenseBean>() {


    override val url: String
        get() = UrlConfig.BANK_INCOME_EXPENSE_LIST

    override val itemLayoutRes: Int
        get() = R.layout.list_item_common_display

    override val httpParams: MutableList<Pair<String, String>>
        get() {
            val type = if (title == DefaultConfig.FUNC_GENERAL_EXPENSE) "支出" else "收入"
            return mutableListOf("type" to type)
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        topBarRightImage {
            activityForResult<IncomeExpenseAddActivity>(Constants.TITLE to title) {
                refresh()
            }
        }
    }

    override fun itemViewConvert(adapter: SlimAdapter, injector: ViewInjector, bean: IncomeExpenseBean, position: Int) {
        val statementAmount = bean.statementList.map { it.money }.sum()
        val balance = bean.money - statementAmount
        injector.text(R.id.tv_title, bean.purpose)
            .text(R.id.tv_subtitle, bean.money.toString() + " | " + balance)
            .text(R.id.tv_bottom_right, bean.remark)
            .onActionLongClicked(
                "删除" to {
                    if (bean.balance == bean.money) {
                        messageDialog(msg = "是否删除${bean.type + bean.purpose}?") { _, _ ->
                            httpGet<IncomeExpenseBean>(UrlConfig.BANK_INCOME_EXPENSE_DELETE,
                                config = {
                                    listParams = listOf("id" to bean.ID)
                                }
                            ) {
                                refresh()
                            }
                        }
                    } else {
                        toast("有关联对账单，禁止删除")
                    }
                },
                "对账单" to {
                    toStatementActivity(title, bean.ID, bean.money) {
                        refresh()
                    }
                }
            )
    }

}